﻿using System;
using System.Text.RegularExpressions;

namespace Bonobo.Irc
{
    [Serializable]
    public struct IrcNickname : IEquatable<IrcNickname>
    {
        private readonly String _value;

        public IrcNickname(String nickname)
        {
            if (!NickRegex.IsMatch(nickname))
            {
                throw new ArgumentException(Resources.IrcNickname_InvalidNickname, "nickname");
            }

            _value = nickname;
        }

        public String Value
        {
            get { return _value; }
        }

        public override Int32 GetHashCode()
        {
            return IrcStringComparer.OrdinalIgnoreCase.GetHashCode(Value);
        }

        public Boolean Equals(IrcNickname other)
        {
            return IrcStringComparer.OrdinalIgnoreCase.Equals(Value, other.Value);
        }

        public override Boolean Equals(Object obj)
        {
            if (obj is IrcNickname)
            {
                return Equals((IrcNickname)(obj));
            }

            return false;
        }

        public override string ToString()
        {
            return _value;
        }

        public static Boolean operator ==(IrcNickname left, IrcNickname right)
        {
            return left.Equals(right);
        }

        public static Boolean operator !=(IrcNickname left, IrcNickname right)
        {
            return !left.Equals(right);
        }

        private static readonly Regex NickRegex = new Regex(
            @"^[a-zA-Z\x5b-\x60\x7b-\x7d]([0-9a-zA-Z\x5b-\x60\x7b-\x7d]|-){0,8}$",
            RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline);
    }
}
